# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2022/4/25


# 获取host
import base64
from time import sleep

import requests

from config.private_config import HAOI_URL
from submodules.common.lib.log_ import get_logger

from submodules.common.lib.datetime_ import get_timestamp, get_timestamp_ms

logger = get_logger()


def get_host():
    host_info = requests.get(f"{HAOI_URL}")
    # ===sv16.haoi23.net:8009--sv15.haoi23.net:8009+++
    host_list = host_info.text.strip("===").strip("+++").split("--")
    for host in host_list:
        res = requests.get(f"http://{host}")
        if res.status_code == 200:
            return host
        else:
            return None


def get_verify_code_by_haoi(img_path):
    # 超时时间/秒
    timeout = 20  # 只能设置20 设置低了不生效
    # 发题
    f = open(img_path, "rb")
    img = base64.b64encode(f.read())

    params = {
        "userstr": f"17744555659|0EB5309ACF167733|t:{timeout}",
        # "gameid": "1005",
        # "gameid": "5001",
        "gameid": "X5001",
        "timeout": f"{timeout}",  # 秒
        "rebate": "6146|4E1B49733BE2BB37",
        "daiLi": "haoi",
        "kou": "0",
        "beizhu": "",
        "ver": "web2",
        "key": f"{get_timestamp_ms()[-10:]}",
        "Img": img,
    }
    request_url = f"http://{get_host()}/UploadBase64.aspx"
    headers = {"content-type": "application/x-www-form-urlencoded"}

    for i in range(timeout):
        # 容错，有时会请求失败 2022-09-02老君发怒了~
        sleep(1)
        try:
            response = requests.post(request_url, data=params, headers=headers)
            tid = response.text
            logger.info(f"response:{response}")
            logger.info(f"tid:{tid}")
        except:
            tid = ""
        # tid = "1005_15_2601002028B0406010"
        if tid.__len__() > 0:
            logger.info(f"final_tid:{tid}")
            break

    # 获取答案
    params = {
        "id": f"{tid}",
        "r": f"{get_timestamp_ms()}",
    }
    request_url = f"http://{get_host()}/GetAnswer.aspx"
    headers = {"content-type": "application/x-www-form-urlencoded"}

    for i in range(timeout):
        sleep(1)
        try:
            response = requests.post(request_url, data=params, headers=headers)
            answer = response.text
            logger.info(f"answer:{answer}")
        except:
            answer = ""
        if answer.__len__() > 0:
            break

    logger.info(f"final_answer:{answer}")
    return answer


if __name__ == "__main__":

    def __test_get_host():
        res = get_host()
        print(res)

    def __test_get_verify_code():
        img_path = "D:\元素-老君查岗页面_验证码区域_带标题.png"
        res = get_verify_code_by_haoi(img_path)
        print(res)

    __test_get_verify_code()

    # __test_get_host()
